package com.xijiekou.sifasuomax.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xijiekou.sifasuomax.MainActivity;
import com.xijiekou.sifasuomax.MyApp;
import com.xijiekou.sifasuomax.R;
import com.xijiekou.sifasuomax.activity.BaseActivity;
import com.xijiekou.sifasuomax.activity.LoginActivity;
import com.xijiekou.sifasuomax.activity.MineMessageActivity;
import com.xijiekou.sifasuomax.activity.ResetPassWordActivity;
import com.xijiekou.sifasuomax.bean.PostRequestBean;
import com.xijiekou.sifasuomax.model.BaseModel;
import com.xijiekou.sifasuomax.model.CheckVersionModel;
import com.xijiekou.sifasuomax.model.LogoutModel;
import com.xijiekou.sifasuomax.model.PhotoUploadModel;
import com.xijiekou.sifasuomax.utils.CommonUtils;
import com.xijiekou.sifasuomax.utils.DownLoadService;
import com.xijiekou.sifasuomax.utils.IntentUtils;
import com.xijiekou.sifasuomax.utils.NewWorkUtils;
import com.xijiekou.sifasuomax.utils.SharePreferenceUtils;
import com.xijiekou.sifasuomax.utils.ToastUtils;
import com.xijiekou.sifasuomax.view.CircleImageView;
import com.xijiekou.sifasuomax.view.UserMessageItemView;
import com.yuyh.library.imgsel.ImgSelActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.xijiekou.sifasuomax.utils.ConstantsUtils.bean;


/**
 * Created by zhouzhuo on 2017/7/4.
 */
public class MineFragment extends BaseFragment{
    private static final int REQUEST_CODE_PHOTO = 0;
    private UserMessageItemView ll_notice,ll_check_update ,ll_clear_cache ,ll_modify_password;
    private CircleImageView iv_photo;
    private TextView tv_login_out,tv_name ,tv_phoneNumber;


    private String appUrl;
    private MyHandler handler;
    private Activity activity;

    private class MyHandler extends Handler {
        private WeakReference<MineFragment> weakReference;
        private MyHandler(MineFragment mineFragment){
            weakReference = new WeakReference<>(mineFragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(weakReference.get()!=null){
                switch (msg.what){
                    case 1:
                        String message = (String) msg.obj;
                        if(!TextUtils.isEmpty(message)){
                            ToastUtils.showShort(getActivity(),message);
                        }
                        break;
                    case 20:
                        String photo = (String) msg.obj;
                        if(!TextUtils.isEmpty(photo)){
                            Log.d("zhouzhuo","上传图片成功:"+photo);
                            SharePreferenceUtils.put(getContext(),"photo",photo);
                            Glide.with(getActivity()).load(photo).into(iv_photo);
                        }
                        break;
                    case 21:
                        iv_photo.setImageResource(R.drawable.user_photo_default);
                        break;

                }
            }
        }
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_mine, null);
        handler = new MyHandler(this);
        activity = getActivity();
        initView(view);
        setMessage();
        return view;
    }

    public void setMessage() {
        String number = (String) SharePreferenceUtils.get(getContext(),"loginname","");
        String photo =(String) SharePreferenceUtils.get(getContext(),"photo","");
        String name = (String) SharePreferenceUtils.get(getContext(),"name","");
        if(!TextUtils.isEmpty(name)){
            tv_name.setText(name);
        }
        if(!TextUtils.isEmpty(number)) {
            tv_phoneNumber.setText(number);
        }
        Log.d("zhouzhuo","设置头像=="+photo);
        if(!TextUtils.isEmpty(photo)){
            Glide.with(getContext()).load(photo).into(iv_photo);
        }
        ll_check_update.setVsesion(CommonUtils.getVersionName(getActivity()));
    }




    private void initView(View view) {
        ll_notice = (UserMessageItemView) view.findViewById(R.id.ll_notice);
        ll_notice.setData(0);
        ll_notice.setOnClickListener(this);
        ll_check_update = (UserMessageItemView) view.findViewById(R.id.ll_check_update);
        ll_check_update.setData(1);
        ll_check_update.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                update();

            }
        });
        ll_check_update.setVsesion(CommonUtils.getVersionName(getActivity()));
        ll_clear_cache = (UserMessageItemView) view.findViewById(R.id.ll_clear_cache);
        ll_clear_cache.setData(2);
        ll_clear_cache.setOnClickListener(this);
        ll_modify_password = (UserMessageItemView) view.findViewById(R.id.ll_modify_password);
        ll_modify_password.setData(3);
        ll_modify_password.setOnClickListener(this);
        iv_photo = (CircleImageView) view.findViewById(R.id.iv_photo);
        iv_photo.setOnClickListener(this);
        tv_login_out = (TextView) view.findViewById(R.id.tv_login_out);
        tv_login_out.setOnClickListener(this);
        tv_name = (TextView) view.findViewById(R.id.tv_name);
        tv_phoneNumber = (TextView) view.findViewById(R.id.tv_phoneNumber);
    }

    private void update(){
        if(!NewWorkUtils.isConnected(getActivity())){
            ToastUtils.showShort(getActivity(),"当前网络不好");
            return;
        }

        CheckVersionModel model = new CheckVersionModel();
        model.setCallBackListener(new BaseModel.CallBackListener<String>() {
            @Override
            public void success(String message)  {
                if(message!=null){
                    try {
                        JSONObject object = new JSONObject(message);
                        if(object.getInt("code")==1){
                            JSONObject object1 = object.getJSONObject("data");
                            appUrl = object1.getString("url");
                            //remark  === 提示信息
                            Log.d("zhouzhuo","appUrl:"+appUrl);
                            showDownloadDialog(object1.getString("remark"));
                        }else {
                            ToastUtils.showShort(getActivity(),object.getString("data"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
            @Override
            public void failed() {

            }
        });
       model.check(CommonUtils.getVersionCode(getActivity()));
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        Intent intent;
        switch (view.getId()){
            case R.id.iv_photo:
               ImgSelActivity.startActivity(getActivity(), MyApp.config, REQUEST_CODE_PHOTO);
                break;
            case R.id.tv_login_out:
                LogoutModel logoutModel = new LogoutModel();
                String number = (String) SharePreferenceUtils.get(getActivity(),"loginname","");
                logoutModel.setCallBackListener(new BaseModel.CallBackListener<String>() {
                    @Override
                    public void success(String message) {
                        if(!TextUtils.isEmpty(message)){
                            PostRequestBean postRequestBean = new Gson().fromJson(message,PostRequestBean.class);
                            if(postRequestBean.code == 1){
                                logout();
                            }
                        }
                    }

                    @Override
                    public void failed() {

                    }
                });

                logoutModel.logout(number);

                break;
            case R.id.ll_modify_password:
                intent = new Intent(getActivity(), ResetPassWordActivity.class);
                IntentUtils.startFragmentToActivity(this,intent,false,0);
                break;
            case R.id.ll_clear_cache:
                ToastUtils.showShort(getContext(),"缓存清理完成");
                break;
            case R.id.ll_notice:
                intent = new Intent(getActivity(), MineMessageActivity.class);
                IntentUtils.startFragmentToActivity(this,intent,false,0);
                break;

        }
    }

    private void logout(){
        Intent intent = new Intent(getActivity(),LoginActivity.class);
        IntentUtils.startFragmentToActivity(this,intent,false,0);
        bean = null;
        SharePreferenceUtils.put(getActivity(),"login","");
        getActivity().finish();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(handler !=null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    //到时候需要改图像在加上
    public void setIcon(String url) {
        compressFile(url);
    }

    public void compressFile(String path){
        final File file = new File(path);
        Luban.with(getActivity())
                .load(file)                     //传人要压缩的图片
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI

                    }
                    @Override
                    public void onSuccess(File file2) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        setIcon2(file2.getPath());

                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();    //启动压缩
    }

    private void setIcon2(String path) {
        PhotoUploadModel uploadModel = new PhotoUploadModel();
        uploadModel.photoUpload(getActivity(),(String)SharePreferenceUtils.get(getActivity(),"id",""),path);
        ToastUtils.showShort(getActivity(),"图片上传中");
        uploadModel.setCallBackListener(new BaseModel.CallBackListener<String>() {
            @Override
            public void success(String str) {
                try {
                    JSONObject object = new JSONObject(str);
                    int  code = object.getInt("code");
                    if(code == 1){
                        String photo = object.getJSONObject("data").getString("url");
                        Message message = Message.obtain();
                        message.what = 20;
                        message.obj = photo;
                        handler.sendMessage(message);
                    }else {
                        Message message = Message.obtain();
                        message.what = 21;
                        message.obj = object.getString("data");
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    Log.d("zhouhzhou","解析异常:"+e.toString());
                    e.printStackTrace();
                    upLoadFailed();
                }

            }

            @Override
            public void failed() {
                upLoadFailed();
            }
        });
    }

    private void upLoadFailed(){
        Message message = Message.obtain();
        message.what = 21;
        message.obj = "图片上传失败";
        handler.sendMessage(message);
    }

    /**
     * 弹出下载框
     */
    private void showDownloadDialog(final String remark) {
        ToastUtils.showShort(getActivity(),"正在更新,更新进度请下拉通知栏查看");
        // 下载apk
        ((MainActivity)getActivity()).requestPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}
                , new BaseActivity.PermissionHandler() {
                    @Override
                    public void onGranted() {
                        downloadApk(remark);
                    }

                    @Override
                    public void onDenied() {

                    }

                    @Override
                    public boolean onNeverAsk() {
                        return false;
                    }
                });

    }
    private void downloadApk(String remark) {
        Intent service = new Intent(getActivity(), DownLoadService.class);
        service.putExtra("downloadurl",appUrl);
        service.putExtra("remark",remark);
        activity.startService(service);
    }


    public abstract class OnMultiClickListener implements View.OnClickListener{
        // 两次点击按钮之间的点击间隔不能少于1000毫秒
        private static final int MIN_CLICK_DELAY_TIME = 5000;
        private long lastClickTime;

        public abstract void onMultiClick(View v);

        @Override
        public void onClick(View v) {
            long curClickTime = System.currentTimeMillis();
            if((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
                // 超过点击间隔后再将lastClickTime重置为当前点击时间
                lastClickTime = curClickTime;
                onMultiClick(v);
            }
        }
    }


}
